﻿package  com.devilcat.ws{
	import com.devilcat.ws.Basicws;
	import com.worlize.websocket.*;
	import com.devilcat.dt.Gamedt;
	import com.devilcat.ob.OtherPlayer;
	
	public class LoadPlayerListws extends Basicws{
		public function LoadPlayerListws() {
			super("iw-protocol");
		}
		override function handleWebSocketOpen(event:WebSocketEvent):void
		{
		}
		public function Update(miles){
			var pack:Object = new Object();
			pack.miles=miles;
			pack.map=Gamedt.Player.map;
			pack.uid=Gamedt.Player.uid;
			pack.action="loadplayerlist";
			var myJson:String = JSONString(pack);
			websocket.sendUTF(myJson);			
		}
		override function handleWebSocketMessage(event:WebSocketEvent):void
		{
			if (event.message.type === WebSocketMessage.TYPE_UTF8)
			{	
				//OtherPlayerList
			//trace("Player List "+event.message.utf8Data);
				var playerList:Array = new Array();
				try{
					playerList =	JSONObject(event.message.utf8Data);
					//trace("playerList "+playerList.length);
					for (var i= 0; i<playerList.length;i++){
						var addNew:Boolean=true;
						for( var j = 0; j <Gamedt.OtherPlayerList.length;j++){
							if(Gamedt.OtherPlayerList[j].uid==playerList[i].uid){
								addNew=false;
								break;
							}
						}
						if(addNew){
							var newPlayer:OtherPlayer = new OtherPlayer(playerList[i].uid,playerList[i].username);
							newPlayer.x=Math.round(Math.random()*1000);
							newPlayer.y=65;
							Gamedt.OtherPlayerList.push(newPlayer);
							Gamedt.MainUI.RootWorldObject.NPCObject.addChild(newPlayer);
						}
					}
				}catch(error:Error){}
				//trace("Gamedt.OtherPlayerList "+Gamedt.OtherPlayerList.length);
			}
		}

	}
	
}
